package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request1, ServletResponse response1, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) request1;
        HttpServletResponse response = (HttpServletResponse) response1;
        HttpSession session = request.getSession();

        //1. 获取用户url
        String requestURI = request.getRequestURI();
        log.info("开始拦截了：{}",requestURI);

        //2. 放行页面和登录相关的接口（白名单）
        String[] uris = {
                "/front/**",
                "/backend/**",
                "/employee/login",
                "/employee/logout",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //判断是否在白名单中
        boolean check = check(uris,requestURI);

        if (check){
            log.info("白名单放行通过:{}",requestURI);
            //放行
            chain.doFilter(request, response);
            //终止程序，不让继续往下走
            return;
        }

        //3. 登录成功，直接放行
        Object empId = session.getAttribute("empId");
        if (empId != null){

            log.info("线程id={}",Thread.currentThread().getId());

            //存入登录的ID - 存入线程空间
            BaseContext.setCurrentId((Long) empId);

            log.info("登录通过:{}",requestURI);

            //放行
            chain.doFilter(request, response);
            //终止程序，不让继续往下走
            return;
        }

        //最后 拦截不允许通过的页面 ， 响应一个结果NOTLOGIN
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 路径匹配器
     * @param uris
     * @param requestURI
     * @return
     */
    public boolean check(String[] uris, String requestURI){
        AntPathMatcher matcher = new AntPathMatcher();
        for (String uri : uris) {
            boolean match = matcher.match(uri, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
